package com.lyxmaster.lib.bluetooth;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import com.lyxmaster.lib.R;
import com.lyxmaster.lib.circledialog.CircleDialog;
import com.lyxmaster.lib.view.BaseActivity;

/**
 * Created by LYX on 2018/3/22.
 */

public class BluetoothActivity extends BaseActivity {
    /**
     * 打开蓝牙回调接口
     */
    public interface OnOpenBtClickListener {
        void onOpenBlutooth(String data);

        void onCancleOpenBluetooth(String data);
    }
    public OnOpenBtClickListener onOpenBtClickListener;
    public void setOnOpenBtClickListener(OnOpenBtClickListener onOpenBtClickListener){
        this.onOpenBtClickListener = onOpenBtClickListener;
    }

    /**
     * 接收蓝牙数据回调接口
     */
    public interface OnRecvBtDataClickListener {
        void onRecvData(byte[] data);
    }
    public OnRecvBtDataClickListener onRecvBtDataClickListener;
    public void setOnRecvBtDataClickListener(OnRecvBtDataClickListener onRecvBtDataClickListener){
        this.onRecvBtDataClickListener = onRecvBtDataClickListener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        init();
    }

    private void init(){
        getPermission();

        context = this;
        activity = this;
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        //提示开启蓝牙
        if(btAdapter!=null && !btAdapter.isEnabled())
        {
            new CircleDialog.Builder(this)
                    .setTitle(getString(R.string.tip))
                    .setText(getString(R.string.bt_notopen))
                    .setPositive(getString(R.string.positive), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                            ((Activity)context).startActivityForResult(enableBtIntent, 0);
                        }
                    })
                    .setNegative(getString(R.string.negative), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if(onOpenBtClickListener != null) onOpenBtClickListener.onCancleOpenBluetooth("");
                        }
                    }).show();
        }

        //绑定BtService服务
        Intent intentSeviceBt = new Intent(this, BtService.class);
        bindService(intentSeviceBt,serviceConnection,BIND_AUTO_CREATE);

        //注册从btservier发来的接收数据广播
        IntentFilter filter = new IntentFilter(BtService.ACTION_BLUTOOTHRECVDATA);
        this.registerReceiver(myReceiver, filter);
    }

    //服务的conn对象
    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 建立连接
            // 获取服务的操作对象
            BtService.MyBinder binder = (BtService.MyBinder) service;
            binder.getService();// 获取到的Service即MyService
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 连接断开
        }
    };

    /**
     * 6.0以上系统获取权限
     */
    private void getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] pers = new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
//                    Manifest.permission.CAMERA,
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.VIBRATE,
//                    Manifest.permission.WAKE_LOCK
            };
            int permissionCheck = 0;
            for(String temp : pers){
                permissionCheck += this.checkSelfPermission(temp);
            }
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions( // 请求授权
                        pers,0);// 自定义常量,任意整型
            } else {
                Log.d("li", "onRequestPermissionsResult: OK");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 0:
                if (hasAllPermissionGranted(grantResults)) {
                    Log.d("li", "onRequestPermissionsResult: OK");
                } else {
                    finish();
                }
                break;
        }
    }

    private boolean hasAllPermissionGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        this.unbindService(serviceConnection);
        this.unregisterReceiver(myReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // requestCode 与请求开启 Bluetooth 传入的 requestCode 相对应
        if (requestCode == 0) {     //是否开启蓝牙
            switch (resultCode) {
                // 点击确认按钮
                case Activity.RESULT_OK:
                {
                    // TODO 用户选择开启 Bluetooth，Bluetooth 会被开启
                    if(onOpenBtClickListener != null) onOpenBtClickListener.onOpenBlutooth("");
                }
                break;

                // 点击取消按钮或点击返回键
                case Activity.RESULT_CANCELED:
                {
                    // TODO 用户拒绝打开 Bluetooth, Bluetooth 不会被开启
                    finish();
                }
                break;
                default:
                    break;
            }
        }
    }

    /**
     * 监听BtService发送的蓝牙接收数据的广播
     */
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(BtService.ACTION_BLUTOOTHRECVDATA.equals(intent.getAction())){
                byte[] data = intent.getByteArrayExtra(BtService.EXTRA_BLUTOOTHRECVDATA);
                if(onRecvBtDataClickListener != null) onRecvBtDataClickListener.onRecvData(data);
            }
        }
    };
}
